/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EstadisticaRentabilidadAula.java
 *
 * Created on 10-dic-2011, 17:29:08
 */
package com.bytecodes.eaulas.estadisticas;

import com.bytecodes.eaulas.beans.Aula;
import com.bytecodes.eaulas.beans.Reserva;
import com.bytecodes.eaulas.beans.Usuario;
import com.bytecodes.eaulas.comun.servicios.EAulasServiciosInterface;
import com.bytecodes.eaulas.comun.servicios.TDSLanguageUtils;
import java.awt.Color;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileFilter;
import java.io.FileWriter;
import java.io.IOException;
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Riki
 */
public class EstadisticaOcupacionAula extends javax.swing.JPanel {

    private EAulasServiciosInterface remoto; 
    
    
    /** Creates new form EstadisticaRentabilidadCliente */
    public EstadisticaOcupacionAula() {
        initComponents();
        cargarCombo();
    }
    public EstadisticaOcupacionAula(EAulasServiciosInterface rem, Usuario user) {
        //throw new UnsupportedOperationException("Not yet implemented");
        
        remoto = rem;        
        initComponents(); 
        cargarCombo();
    }

    private void cargarCombo(){
        // Cargar datos de desplegables

       try {             
            List<Aula> listaAulas;        
            listaAulas = remoto.consultaAulas();        
            jComboBox1.addItem("");
            String item;
        for (Aula obj : listaAulas) {
            
                item = ( obj.getId() + " - "
                        + obj.getDescripcion().trim());
                jComboBox1.addItem(item);
            
        }           
          } catch (RemoteException ex) {
            ex.printStackTrace();
        }  
       
    }    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        
        this.setBackground(Color.WHITE);
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        jLabel1.setText(TDSLanguageUtils.getMessage("orden.reixa.capcelera.SpaceId"));
        jLabel1.setName(TDSLanguageUtils.getMessage("orden.reixa.capcelera.SpaceId"));  
        jLabel2.setText(TDSLanguageUtils.getMessage("estadisticasRentabilidadCliente.datos.fechaInicio"));
        jLabel2.setName(TDSLanguageUtils.getMessage("estadisticasRentabilidadCliente.datos.fechaInicio")); 
        jLabel3.setText(TDSLanguageUtils.getMessage("estadisticasRentabilidadCliente.datos.fechaFin"));
        jLabel3.setName(TDSLanguageUtils.getMessage("estadisticasRentabilidadCliente.datos.fechaFin"));

        jComboBox1.setName(TDSLanguageUtils.getMessage("panelGestionUsuarios.TipoUsu.Cliente"));         
        jTextField1.setName(TDSLanguageUtils.getMessage("estadisticasRentabilidadCliente.datos.fechaInicio"));         
        jTextField2.setName(TDSLanguageUtils.getMessage("estadisticasRentabilidadCliente.datos.fechaFin")); 

        jLabel4.setText(TDSLanguageUtils.getMessage("estadisticasOcupacionAula"));
        jLabel4.setName(TDSLanguageUtils.getMessage("estadisticasOcupacionAula")); 
        jLabel4.setForeground(new Color(255, 51, 51));

        jButton1.setText(TDSLanguageUtils.getMessage("panelGestionRecurso.buscar"));
        jButton1.setName(TDSLanguageUtils.getMessage("panelGestionRecurso.buscar")); 
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });           

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] { 
                
            },
            new String [] {
                TDSLanguageUtils.getMessage("orden.reixa.capcelera.SpaceId"), 
                TDSLanguageUtils.getMessage("mostrar.lbl2"), 
                TDSLanguageUtils.getMessage("estadisticasRentabilidadCliente.datos.fechaInicio"), 
                TDSLanguageUtils.getMessage("estadisticasRentabilidadCliente.datos.fechaFin"), 
                TDSLanguageUtils.getMessage("estadisticas.ocupacion.horainicio"), 
                TDSLanguageUtils.getMessage("estadisticas.ocupacion.horafin"), 
                TDSLanguageUtils.getMessage("estadisticas.ocupacion.pax")                
            }
        ));
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane1.setViewportView(jTable1);
        jTable1.setVisible(false);

        jLabel5.setText(TDSLanguageUtils.getMessage("estadisticas.resultado"));
        jLabel5.setName(TDSLanguageUtils.getMessage("estadisticas.resultado")); 
        jLabel5.setVisible(false);
        jButton2.setText(TDSLanguageUtils.getMessage("estadisticas.exportar"));
        jButton2.setName(TDSLanguageUtils.getMessage("estadisticas.exportar")); 
        jButton2.setVisible(false);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

       jButton3.setText(TDSLanguageUtils.getMessage("orden.mensaje.cancelar")); 
        jButton3.setName(TDSLanguageUtils.getMessage("orden.mensaje.cancelar"));         
        jButton3.setVisible(false);        
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        
        // Defino anchura y altura del formulario
        //                
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()                
                .addContainerGap(1000, Short.MAX_VALUE))
        );
        
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()                
                .addContainerGap(500, Short.MAX_VALUE))
        );

	this.setBackground(Color.WHITE);                
        // Coloco componentes
        // Columna, Fila, Anchura y altura
        
        jLabel4.setBounds(new Rectangle(500, 10, 380, 16));
        jLabel4.setForeground(new Color(255, 51, 51));
	jLabel1.setBounds(new Rectangle(30,40,75,20));
	jLabel2.setBounds(new Rectangle(30,70,75,20));
	jLabel3.setBounds(new Rectangle(30,100,750,20));

	this.add(jLabel1,null);
	this.add(jLabel2,null);
	this.add(jLabel3,null);
	this.add(jLabel4,null);
        
	jComboBox1.setBounds(new Rectangle(110,40,150,20));
        jTextField1.setBounds(new Rectangle(110,70,100,20));
        jTextField2.setBounds(new Rectangle(110,100,100,20));              
        // Solo dejamos entrar numeros
        jTextField1.addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
            char caracter = e.getKeyChar();
            boolean bien = true;
            if (caracter == '/') bien = false;
            if ((caracter >= '0') && (caracter <= '9')) bien = false;
            if (jTextField1.getText().length() > 9) bien = true;
            if (bien) e.consume();
            }
        });
        // Solo dejamos entrar numeros
        jTextField2.addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
            char caracter = e.getKeyChar();
            boolean bien = true;
            if (caracter == '/') bien = false;
            if ((caracter >= '0') && (caracter <= '9')) bien = false;
            if (jTextField2.getText().length() > 9) bien = true;
            if (bien) e.consume();
            }
        });
        
	this.add(jComboBox1,null);
	this.add(jTextField1,null);
	this.add(jTextField2,null);
        
        jButton1.setBounds(new Rectangle(200,150,100,30));
	this.add(jButton1,null);
        
        // Graella de dades
        jScrollPane1.setBounds(new Rectangle(20,200,950,240));
        this.add(jScrollPane1,null);
        //
        jButton2.setBounds(new Rectangle(700,450,150,30));
	this.add(jButton2,null);
        
        jButton3.setBounds(new Rectangle(500,450,150,30));
	this.add(jButton3,null);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        List<Reserva> datos;
        String fechaInicio = null;
        String fechaFin = null;
        String spaceid = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        try {
            if (!jTextField1.getText().equals("")) {
                fechaInicio = jTextField1.getText();
                dateFormat.parse(fechaInicio);

            }
            if (!jTextField2.getText().equals("")) {
                fechaFin = jTextField2.getText();
                dateFormat.parse(fechaFin);

            }
            if (!((String) jComboBox1.getSelectedItem()).equals("")) {
                spaceid = (String) jComboBox1.getSelectedItem();
                String[] id = spaceid.split(" ");
                spaceid = id[0];
            }

            jTextField1.setEditable(false);
            jTextField2.setEditable(false);
            jComboBox1.setEnabled(false);
            jButton1.setVisible(false);
            jLabel5.setVisible(true);
            jTable1.setVisible(true);
            jButton2.setVisible(true);
            jButton3.setVisible(true);

            datos = remoto.getDatosEstOcupacion(spaceid, fechaInicio, fechaFin, "aula");
            
            if(datos.isEmpty()){
                JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("estadisticas.error.sinresultados"),
                    TDSLanguageUtils.getMessage("estadisticas.error"),
                    JOptionPane.ERROR_MESSAGE);
                 jButton2.setVisible(false);
                 jButton1.setVisible(true);
                 jButton3.setVisible(false);
                 jTextField1.setEditable(true);
                 jTextField2.setEditable(true);
                 jComboBox1.setEnabled(true);
            }
            
            montarDatosTabla(datos);

        } catch (RemoteException ex) {
            ex.printStackTrace();
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("estadisticas.error.fecha"),
                    TDSLanguageUtils.getMessage("estadisticas.error"),
                    JOptionPane.ERROR_MESSAGE);

        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void montarDatosTabla(List<Reserva> datos) {

        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        Integer participantes = 0;
        Integer rowTable = 0;
        String spaceid = "";        
        String userid = "";
        Timestamp fecha1 = null;
        Timestamp fecha2 = null;
        String fechaInicio = null;
        String fechaFin = null;
        String horaInicio = "";
        String horaFin = "";        
        

        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        for (Reserva obj : datos) {
            spaceid = (obj.getIdAula()).toString();
            participantes = obj.getNumeroOcupantesAula();
            userid = obj.getIdUsuario();
            fechaInicio = df.format(obj.getFechaPeticionInicioReserva());
            fechaFin = df.format(obj.getFechaPeticionFinReserva());            
            fecha1 = (Timestamp) obj.getFechaPeticionInicioReserva();
            fecha2 = (Timestamp) obj.getFechaPeticionFinReserva();
            horaInicio = obtenerHora(fecha1);
            horaFin = obtenerHora(fecha2);

            if (rowTable.intValue() == 0) {
                modelo.addRow(new Object[]{spaceid, userid, fechaInicio, fechaFin, horaInicio, horaFin, participantes});
            } else {
                modelo.insertRow(rowTable, new Object[]{spaceid, userid, fechaInicio, fechaFin, horaInicio, horaFin, participantes});
            }
            rowTable++;            

        }
        if (rowTable.intValue() == 0) {
            JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("estadisticas.error.sinresultados"),
                    TDSLanguageUtils.getMessage("estadisticas.error"),
                    JOptionPane.ERROR_MESSAGE);
            jButton2.setVisible(false);
            jButton3.setVisible(false);
            jButton1.setVisible(true);
            jTextField1.setEditable(true);
            jTextField2.setEditable(true);
            jComboBox1.setEnabled(true);
        }
    }
    
    private String obtenerHora(Date fecha){
        
        Calendar calendario = Calendar.getInstance();
        StringBuilder horaCompleta = new StringBuilder();
        Integer hora, minuto, segundo = 0;
        calendario.setTime(fecha);
        hora = calendario.get(Calendar.HOUR_OF_DAY);
        minuto = calendario.get(Calendar.MINUTE);
        segundo = calendario.get(Calendar.SECOND);
        horaCompleta.append(hora);
        horaCompleta.append(":");
        horaCompleta.append(minuto);
        horaCompleta.append(":");
        horaCompleta.append(segundo);
        
        return horaCompleta.toString();
    }
    
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
       try {
            String fichero = ExportacionListados.exportTable(jTable1);
            JFileChooser fc = new JFileChooser(System.getProperty("user.dir"));
            //FileFilter filter1 = new ExtensionFileFilter("JPG and JPEG", new String[] { "JPG", "JPEG" });
            fc.showSaveDialog(this); //Muestra el diálogo
            
            File Guardar = fc.getSelectedFile();
            if (Guardar != null) {
                FileWriter Guardx = new FileWriter(Guardar);
                Guardx.write(fichero);
                Guardx.close(); //Cierra el fichero
            }
        } catch (IOException ioe) {
            System.out.println(ioe); //Muestra por consola los errores
        }
    }//GEN-LAST:event_jButton2ActionPerformed
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
                
            jTextField1.setEditable(true);
            jTextField2.setEditable(true);
            jComboBox1.setEnabled(true);
            jButton1.setVisible(true);
            jLabel5.setVisible(false);
            jTable1.setVisible(false);
            jButton2.setVisible(false);
            jButton3.setVisible(false);
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] { 
                
            },
            new String [] {
                    TDSLanguageUtils.getMessage("orden.reixa.capcelera.SpaceId"), 
                    TDSLanguageUtils.getMessage("mostrar.lbl2"), 
                    TDSLanguageUtils.getMessage("estadisticasRentabilidadCliente.datos.fechaInicio"), 
                    TDSLanguageUtils.getMessage("estadisticasRentabilidadCliente.datos.fechaFin"), 
                    TDSLanguageUtils.getMessage("estadisticas.ocupacion.horainicio"), 
                    TDSLanguageUtils.getMessage("estadisticas.ocupacion.horafin"), 
                    TDSLanguageUtils.getMessage("estadisticas.ocupacion.pax")                
                }
            ));
            jTable1.setName("jTable1"); // NOI18N

            
        }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration//GEN-END:variables
}
